import React, { useEffect } from 'react';
import styles from './index.less';
import { Button, Select } from 'antd';
import moment from 'moment';
// components
import { PlusCircleOutlined, SwapOutlined, UploadOutlined } from '@/utils/antdIcons';
import Counterparty from './Counterparty'; // 对手方
import DateRangePicker from './DateRangePicker'; // 自定义日期
import Settlement from './Settlement';

export const LATITUDE_OPTIONS = [
  { value: 'month', label: '月' },
  { value: 'day', label: '日' },
  { value: '24', label: '24小时连续' },
  { value: 'stack24', label: '24小时叠加' },
  { value: '96', label: '96点连续' },
  { value: 'stack96', label: '96点叠加' },
];

export default (props) => {
  /** data */
  // (基数维度、时间维度)改变即更新，其他参数点击查询后更新
  const {
    buttonPermissions = [],
    defaultForm = null,
    pageType,
    powerData = [],
    onAction = () => {},
    onChangeForm = () => {},
  } = props;
  const [stations, setStations] = React.useState([]); // 结算单元选项
  const [form, setForm] = React.useState({
    dates: null,
    provinceId: '', // 省份id
    counterpartyList: [], // 对手方
    settlementUnitList: [], // 结算单元
    radixType: '1', // 1 剩余仓位中含基数, 2 合约中含基数
    latitude: 'stack96',
    provinceName: '', // 省份名称
    stationName: '',
    counterpartyTitle: '全部系统对手方',
  });

  useEffect(() => {
    if (pageType === 'main') {
      onChangeProvince(powerData?.[0]?.value, powerData?.[0]);
    } else {
      if (!defaultForm) return;
      form.dates = [moment(defaultForm.st), moment(defaultForm.en)];
      form.provinceId = defaultForm.p;
      form.settlementUnitList = [defaultForm.s];
      form.counterpartyList = defaultForm.c.split(',');
      form.radixType = defaultForm.r;
      form.latitude = defaultForm.l;
      // labels
      form.provinceName = defaultForm.f1;
      form.stationName = defaultForm.f2;
      form.counterpartyTitle = defaultForm.f3;
      setForm(form);
      handleSubmit();
    }
  }, []);

  const updateForm = (values) => {
    setForm({
      ...form,
      ...values,
    });
  };

  const onChangeProvince = (provinceId, opt) => {
    // 切换省份
    const stations = opt?.children || [];
    setStations(stations);
    updateForm({
      provinceId,
      provinceName: opt.label,
      settlementUnitList: _.flatten(stations.map((i) => i?.children?.map((x) => x.stationId))),
    });
  };

  const handleSubmit = () => {
    const { dates, ...other } = form;
    let values = {
      ...other,
      startDate: form.dates[0].format('YYYY-MM-DD'),
      endDate: form.dates[1].format('YYYY-MM-DD'),
    };
    onAction('submit', values);
  };

  // 主页面
  const mainForm = () => (
    <>
      <div className={styles.box}>
        <DateRangePicker value={form.dates} onChange={(v) => updateForm({ dates: v })} />
      </div>
      <div className={styles.box}>
        {/* 省份 */}
        <Select
          style={{ width: '100%', fontSize: 12 }}
          value={form.provinceId}
          onChange={onChangeProvince}
          bordered={false}
          showSearch
          options={powerData}
          optionFilterProp="label"
        />
      </div>
      <div className={styles.box}>
        {/* 对手方 */}
        <Counterparty
          onChange={(v, t) =>
            updateForm({
              counterpartyList: [...v],
              counterpartyTitle: t,
            })
          }
          provinceId={form.provinceId}
          buttonPermissions={buttonPermissions}
        />
      </div>
      <div className={styles.box}>
        {/* 结算单元 */}
        <Settlement
          value={form.settlementUnitList}
          onChange={(v) => updateForm({ settlementUnitList: [...v] })}
          options={stations}
        />
      </div>
    </>
  );

  // 单场 详情页
  const childForm = () => (
    <>
      <div className={styles.box_dis}>
        {form?.dates ? `${form?.dates.map((x) => x.format('MMDD')).join(' - ')}` : ''}
      </div>
      <div className={styles.box_dis}>{form?.provinceName}</div>
      <div className={styles.box_dis}>{form?.counterpartyTitle}</div>
      <div className={styles.box_dis}>{form?.stationName}</div>
    </>
  );

  const latitudeOpts = React.useMemo(
    () => (pageType === 'main' ? [...LATITUDE_OPTIONS] : LATITUDE_OPTIONS.slice(2)),
    [pageType],
  );

  return (
    <div className={styles.tool}>
      {pageType === 'main' && mainForm()}
      {pageType === 'child' && childForm()}
      <div className={styles.box}>
        {/* 基数维度 */}
        <div
          className={styles.radix}
          onClick={() => {
            const radixType = form.radixType === '1' ? '2' : '1';
            updateForm({ radixType });
            onChangeForm({ radixType });
          }}
        >
          <span>{form.radixType === '1' ? '剩余仓位中含基数' : '合约中含基数'}</span>
          <SwapOutlined />
        </div>
      </div>
      <div className={styles.box}>
        {/* 时间维度 */}
        <Select
          style={{ width: '100%', fontSize: 12 }}
          value={form.latitude}
          onChange={(v) => {
            updateForm({ latitude: v });
            onChangeForm({ latitude: v });
          }}
          bordered={false}
          options={latitudeOpts}
        />
      </div>
      <div className={styles.btns}>
        {/* 按钮 */}
        <Button
          type="link"
          icon={<UploadOutlined />}
          style={{ padding: 0 }}
          onClick={() => onAction('export')}
        >
          导出
        </Button>
        {pageType === 'main' && (
          <Button
            className={styles.btn}
            style={{ padding: 0, width: 48 }}
            shape="round"
            size="small"
            type="primary"
            disabled={!form.dates}
            onClick={handleSubmit}
          >
            查询
          </Button>
        )}
        {pageType === 'child' && (
          <Button
            className={styles.btn_link}
            type="link"
            icon={<PlusCircleOutlined />}
            style={{ padding: 0 }}
            onClick={() => onAction('add')}
          >
            新增
          </Button>
        )}
      </div>
    </div>
  );
};
